<template>
  <el-form inline>
    <el-form-item label="连接">
      <el-input v-model="uid" placeholder="请输入用户id"></el-input>
      <el-button @click="conn">建立连接</el-button>
    </el-form-item>
    <el-form-item label="要发给谁">
      <el-input v-model="toUser"></el-input>
    </el-form-item>
    <el-form-item label="消息内容">
      <el-input v-model="msg" placeholder="请输入消息内容"></el-input>
      <el-button @click="send">发送消息</el-button>
    </el-form-item>
  </el-form>
  <h1>收到的消息：</h1>
  <h4 v-for="m in msgList">{{m}}</h4>
</template>

<script setup>
/*用户id、消息*/
import {ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";

let uid = ref('');
let toUser = ref('');
let msg = ref('');
//收到的消息列表
let msgList = ref([]);

/*与socket服务端建立连接*/
let conn = ()=>{
  let ws = new WebSocket('ws://localhost:8081/socket/'+uid.value);
  // 监听收到的消息
  ws.onmessage = (m)=>{
    msgList.value.push(m.data);
  }
}

let send = ()=> {
  axios.post(`/send?uid=${toUser.value}&message=${msg.value}`).then(res => {
    ElMessage.success(res.msg)
  })
}
</script>

<style scoped>

</style>